<?php

namespace app\common\traits;

use app\common\libs\InsideApi;
use think\Exception;

trait WechatTrait
{
    /**
     * 获取授权，跳转授权页面
     */
    public function getOauth($params)
    {
        try {
            $config = config('wechat');
            $scope = !empty($params['scope']) ? "snsapi_userinfo" : "snsapi_base";
            $redirect_url = $this->parseUrl($params, $config);
            $data = ['url' => $redirect_url, 'state' => $params['state'] ?? '', 'client_id' => $config['app_id'] ?? '', 'scope' => $scope];
            $res = InsideApi::Wechat()->Oauth()->GetRedirect($data);
            if (empty($res) || $res['code'] != 200 || empty($res['data'])) {
                api_exception(400, '授权链接获取失败，请重新尝试！');
            }
            return $res['data'] ?? [];
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     *获取微信OPENID
     */
    public function wxOauth($params)
    {
        try {
            $config = config('wechat');
            $data = ['code' => $params['code'] ?? '', 'client_id' => $config['app_id'] ?? ''];
            $res = InsideApi::Wechat()->Oauth()->GetOpenid($data);
            if (empty($res) || $res['code'] != 200) {
                api_exception(400, '微信登录超时，请重新尝试！');
            }
            return $res['data'] ?? [];
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     *获取微信用户信息
     */
    public function wxInfo($params)
    {
        try {
            $config = config('wechat');
            $data = ['openid' => $params['openid'] ?? '', 'client_id' => $config['app_id'] ?? ''];
            $res = InsideApi::Wechat()->Oauth()->GetUserInfo($data);
            if (empty($res) || $res['code'] != 200) {
                api_exception(400, '微信连接超时，请重新尝试！');
            }
            return $res['data'] ?? [];
        } catch (Exception $e) {
            throw $e;
        }
    }

    /**
     * post方法
     * @param array $params
     * @param array $config
     * @return string
     * @throws \yiqiniu\extend\exception\ApiException
     */
    private function parseUrl(array &$params, array $config): string
    {
        $url = '';
        switch ($params['type'] ?? 0) {
            case 1:
                $url = $config['bind_url'] ?? '';//管理员绑定微信
                $params['state'] = $params['admin_id'] ?? 0;
                break;
            case 2:
                $url = $config['login_url'] ?? '';//导购微信登录
                break;
            case 3:
                $url = $config['register_url'] ?? '';//导购注册
                break;
        }
        if (empty($url)) {
            api_exception(400, '跳转回调URL不能为空');
        }
        return $url . '?mkey=' . $params['mer_id'];
    }
}
